package com.example.multithread;

/**
 * 多线程模拟售票系统，目前这种实现方式会有超卖情况。
 */
public class ThreadSynchronizeTest {
    public static int ticket = 5;
    public static void main(String[] args) {
        Runnable body = ()->{
            while (true) {
                if (ticket > 0) {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                    System.out.println("["+Thread.currentThread().getName()+"] 售票，当前的剩余票数: " + (--ticket));
                } else {
                    break;
                }
            }
        };

        for (int i = 0; i < 5; i++) {
            new Thread(body, "sale ticket-" + i).start();
        }
    }
}
